package com.lepu.app.fun.mother_circle.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.application.MyApplication;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.Observer;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.mother_circle.MotherTopicActivity;
import com.lepu.app.fun.mother_circle.adapter.AdapterMotherTopic;
import com.lepu.app.fun.mother_circle.adapter.AdapterMotherTopicShow;
import com.lepu.app.fun.mother_circle.bean.BeanMotherCircle;
import com.lepu.app.fun.mother_circle.bean.BeanMotherTopic;
import com.lepu.app.fun.mother_circle.view.MotherTopicHeadView;
import com.lepu.app.usercenter.bean.LoginInfo;

public class FragmentMotherTopic extends BaseFragment implements AsyncRequest,
		OnRefreshListener, OnLoadListener, Observer {

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;


	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private AdapterMotherTopic mDataAdapter = null;
	private AdapterMotherTopicShow mDataAdapterShow = null; //宝妈一起秀
	private ArrayList<BeanMotherTopic> mDataArrayList = null;
	private ArrayList<BeanMotherTopic> mDataHeadArrayList = null;
	private ArrayList<BeanMotherTopic> mDataBodyArrayList = null;
	
	private int mCurrentPage = 1;
	private boolean mInitDataSuccess = false;

	private View mMainView = null;

	private String mCurrentDate = "";

	private MotherTopicHeadView mMotherTopicHeadView = null;

	public boolean mNeedRefresh = false;

	public int mTopicType = 1;  //1全部 2热帖 3精品
	public BeanMotherCircle mMotherCircle = null;

	@SuppressLint("InflateParams")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mMainView = LayoutInflater.from(getActivity()).inflate(R.layout.mother_show_fragment, null, false);
		init();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		ViewGroup p = (ViewGroup) mMainView.getParent();
		if (p != null) {
			p.removeAllViewsInLayout();
		}
		return mMainView;
	}

	@SuppressLint("DefaultLocale")
	@Override
	public void onDestroy() {
		
		String key = String.format("%s_%d", ObserverConst.NOTIFY_MOTHER_POST_CHANGE,mTopicType);
        ObserverManager.getInstance().removeObserver(key);
        
        super.onDestroy();
		mInitDataSuccess = false;
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);

		if (isVisibleToUser) {
			if (!mInitDataSuccess) {
				
				showFirstLoadDataLayout(true);
				//一个activity加入多个fragment，有些手机不能自动加载更多，需要调一下这个方法，就可以了！！！
				mGoogleRefreshLayout.setRefreshing(true);
				request(false);
			}
		}
	}
	
	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
			}else{
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) mMainView.findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if(mDataArrayList == null || mDataArrayList.size() == 0)
				{
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
				
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	@SuppressWarnings("deprecation")
	@SuppressLint({ "ResourceAsColor", "DefaultLocale" })
	private void init() {
		mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) mMainView.findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
											R.color.color_listview_refresh_2,
											R.color.color_listview_refresh_3,
											R.color.color_listview_refresh_4);
		mDataArrayList = new ArrayList<BeanMotherTopic>();
		mDataHeadArrayList = new ArrayList<BeanMotherTopic>();
		mDataBodyArrayList = new ArrayList<BeanMotherTopic>();
		
		Bundle data = getArguments();
		
		mTopicType = data.getInt("Type");
		mMotherCircle = (BeanMotherCircle) data.getSerializable("MotherCircle");
		
		String key = String.format("%s_%d", ObserverConst.NOTIFY_MOTHER_POST_CHANGE,mTopicType);
        ObserverManager.getInstance().addObserver(key, this);
	}

	//请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
			mCurrentDate="";
		}

		String url = "";

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (MyApplication.getInstance().checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance()
						.getLoginInfo();
				params.put("UserID", loginInfo.UserID);
			} else {
				params.put("UserID", -1);
			}
			
			if(mTopicType == 1){ //全部
				url = Setting.getTopicListUrl();
				params.put("CategoryID", mMotherCircle.cricleID);
				params.put("SortBy", 2);
				params.put("SortDirection", "DESC");
			}else if(mTopicType == 2){//最新
				url = Setting.getTopicListUrl();
				params.put("CategoryID", mMotherCircle.cricleID);
				params.put("SortBy", 1);
				params.put("SortDirection", "DESC");
			}else if(mTopicType == 3){//精华
				url = Setting.getTopicGoodListUrl();
				params.put("CategoryID", mMotherCircle.cricleID);
			}
			

			params.put("RefreshTime", mCurrentDate);
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true,false,true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				
				MotherTopicActivity instance = MotherTopicActivity.getInstance();
				if(instance == null)
				{
					return;
				}

				ArrayList<BeanMotherTopic> dataList = (ArrayList<BeanMotherTopic>) msg.obj;
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataHeadArrayList.clear();
					mDataBodyArrayList.clear();
					mDataArrayList.clear();
					
					if(mMotherTopicHeadView != null){
						mDataListView.removeHeaderView(mMotherTopicHeadView);
					}
					
					//过滤出HeadView 数据
					for(int i=0; i<dataList.size(); i++){
						if(dataList.get(i).topicIsTop == 1){
							mDataHeadArrayList.add(dataList.get(i));
						}else{
							mDataBodyArrayList.add(dataList.get(i));
						}
					}
					
					if(mTopicType == 1){//全部
						if(mMotherCircle.cricleID.equals("2")){ //妈妈圈
							mDataArrayList.addAll(dataList);
							mMotherTopicHeadView = new MotherTopicHeadView(MotherTopicActivity.getInstance(), mTopicType,mMotherCircle,null);
							mDataListView.addHeaderView(mMotherTopicHeadView);
							
							mDataAdapterShow = new AdapterMotherTopicShow(MotherTopicActivity.getInstance(),mDataArrayList,mTopicType);
							mDataListView.setAdapter(mDataAdapterShow);
						}else{
							mDataArrayList.addAll(mDataHeadArrayList);
							mDataArrayList.addAll(mDataBodyArrayList);
							mMotherTopicHeadView = new MotherTopicHeadView(MotherTopicActivity.getInstance(), mTopicType,mMotherCircle,null);
							mDataListView.addHeaderView(mMotherTopicHeadView);
							
							mDataAdapter = new AdapterMotherTopic(MotherTopicActivity.getInstance(),mDataArrayList,mTopicType);
							mDataListView.setAdapter(mDataAdapter);
						}
						
					}else{ // 最新/精华
						mDataArrayList.addAll(dataList);
						mMotherTopicHeadView = new MotherTopicHeadView(MotherTopicActivity.getInstance(), mTopicType,mMotherCircle,null);
						if(mMotherCircle.cricleID.equals("2")){  //妈妈圈
							mDataListView.addHeaderView(mMotherTopicHeadView);
							mDataAdapterShow = new AdapterMotherTopicShow(MotherTopicActivity.getInstance(),mDataArrayList,mTopicType);
							mDataListView.setAdapter(mDataAdapterShow);
							mDataListView.removeHeaderView(mMotherTopicHeadView);
						}else{
							mDataListView.addHeaderView(mMotherTopicHeadView);
							mDataAdapter = new AdapterMotherTopic(MotherTopicActivity.getInstance(),mDataArrayList,mTopicType);
							mDataListView.setAdapter(mDataAdapter);
							mDataListView.removeHeaderView(mMotherTopicHeadView);
						}
						
					}
					
					mInitDataSuccess = true;
				} else {
					//UIHelper.showToast(MotherTopicActivity.getInstance(), R.string.no_data);
                    showHideNoDataLayout(true);
					
					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
				}

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				
				//第一次请求用这个
				showFirstLoadDataLayout(false);

				if (mDataArrayList != null && mDataArrayList.size() > 0) {
					if (mDataArrayList.size() < Setting.PAGE_SIZE) {
						mGoogleRefreshLayout.setLoadMoreFinish(true);
					}
				}else{
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				showFirstLoadDataLayout(false);
				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanMotherTopic> dataMoreList = (ArrayList<BeanMotherTopic>) msg.obj;
				
				if (dataMoreList != null && dataMoreList.size() > 0) {
					
					if(mMotherCircle.cricleID.equals("2")){
						mDataAdapterShow.notifyDataSetChanged();
					}else{
						mDataAdapter.notifyDataSetChanged();
					}

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MotherTopicActivity.getInstance(), R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			mCurrentDate = BeanMotherTopic.parseJsonDate((String) data);
			ArrayList<BeanMotherTopic> dataArraylist = BeanMotherTopic.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mCurrentDate = BeanMotherTopic.parseJsonDate((String) data);
			ArrayList<BeanMotherTopic> dataMoreArraylist = BeanMotherTopic.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					BeanMotherTopic item = dataMoreArraylist.get(i);
					if(item.topicIsTop == 1){
						mDataHeadArrayList.add(item);
					}else{
						mDataBodyArrayList.add(item);
					}
				}
				
				if(mTopicType == 1){
					if(mMotherCircle.cricleID.equals("2")){
						mDataArrayList.addAll(dataMoreArraylist);
					}else{
						mDataArrayList.clear();
						mDataArrayList.addAll(mDataHeadArrayList);
						mDataArrayList.addAll(mDataBodyArrayList);
					}
				}else{
					mDataArrayList.addAll(dataMoreArraylist);
				}
				
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} 
	}

	@Override
	public void notify(String arg0, Object arg1, Object arg2) {
		request(false);
	}

}
